<template>
  <div
    class="float-page"
    id="gtvhelphdx"
    :style="'left:' + point.x + 'px;top:' + point.y + 'px'"
  >
    <img
      @click="toggle()"
      style="
        width: 50px;
        height: 50px;
        cursor: pointer;
        position: fixed;
        z-index: 99;
      "
      src="http://epg.gzgdnm.com/www/epg_-pc_-api_-chrome-plugin/dist/help.JPG"
      draggable="true"
      @dragenter="dragenter($event)"
      @dragend="dragover($event, point)"
      @dragstart="dragstart($event, point)"
    />
    <Card style="position:relative;top:40px;" class="box-card" v-if="show">
      <div slot="header" class="clearfix">
        <Checkbox
          style="float: left;color: #515a6e !important;padding: 2px 0"
          @change="devChange($event)"
          v-model="isDev"
          >测试栏目</Checkbox
        >
        <div style="float: right;">
          <Button @click="refresh()" style="padding: 4px 0" type="text">
          <Icon type="md-refresh"
          /></Button>
          <Button  @click="update()" style="padding: 4px 0" type="text"
            >升级</Button
          >
          <Button style="padding: 4px 0" type="text"
            ><a
              href="dingtalk://dingtalkclient/action/sendmsg?dingtalk_id=hedingxin"
              >请我喝一杯</a
            ></Button
          >
          <Button style="padding: 4px 0" type="text"
            ><a
              href="dingtalk://dingtalkclient/action/sendmsg?dingtalk_id=hedingxin"
              >建议</a
            ></Button
          >
        </div>
      </div>
      <Tabs class="tabls-epg">
        <TabPane label="PC本地模拟">
          <Form ref="form" inline :model="form">
            <FormItem label="账号">
              <Select
                size="small"
                v-model="form.userId"
                filterable
                remote
                :default-label="defaultUser.accountNumber"
                @change="selectU($event)"
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="loading"
              >
                <Option
                  v-for="item in options"
                  :key="item.snowflakeId"
                  :value="item.snowflakeId"
                >
                  {{ item.accountNumber }}
                </Option>
              </Select>
              <Alert>串号:{{ defaultUser.iptvStbImei }}</Alert>
            </FormItem>
            <FormItem label="机顶盒型号">
              <Select
                size="small"
                v-model="form.stbType"
                @change="stbEvent($event)"
                filterable
                placeholder="请输入关键词"
              >
                <Option
                  v-for="(item, index) in stbTypeOptions"
                  :key="index + item"
                  :value="item.name"
                  :label="item.name"
                >
                  <!-- {{ item.name }} -->
                </Option>
              </Select>
            </FormItem>
            <FormItem label="县域">
              <Select
                size="small"
                v-model="form.areas"
                filterable
                @change="changeArea($event)"
                placeholder="请输入关键词"
              >
                <Option
                  v-for="(item, index) in areasOptions"
                  :key="index"
                  :value="item.city"
                >
                  {{ item.name }}
                </Option>
              </Select>
            </FormItem>
            <FormItem label="机顶盒软件版本">
              <Input
                v-model="form.macversion"
                @input="softVersionevent($event)"
                placeholder="机顶盒软件版本"
              ></Input>
            </FormItem>
            <FormItem label="本地PC用户属性">
              <Checkbox
                size="small"
                @change="updateStatusLocal($event, statu)"
                v-for="statu in tags"
                :value="statu.local"
                :key="statu.value"
                >{{ statu.label }}</Checkbox
              >
            </FormItem>
          </Form>
        </TabPane>
        <TabPane label="APP安装">
          模拟安装
          <ul>
            <li @click="an(item)" :key="index" v-for="(item, index) in apkList">
              <span>{{ item.name }}</span> 是否安装:
              <span v-if="check(item.city)">✅</span>
              <span v-else>❎</span>
            </li>
          </ul>
        </TabPane>
        <TabPane label="属性修改">
          <Form ref="form" inline :model="form">
            <FormItem label="账号">
              <Select
                size="small"
                v-model="form.userId"
                filterable
                remote
                :default-label="defaultUser.accountNumber"
                @change="selectU($event)"
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="loading"
              >
                <Option
                  v-for="item in options"
                  :key="item.snowflakeId"
                  :value="item.snowflakeId"
                >
                  {{ item.accountNumber }}
                </Option>
              </Select>
              <Alert>串号:{{ defaultUser.iptvStbImei }}</Alert>
            </FormItem>
            <FormItem label="设置用户属性">
              <Checkbox
                :disabled="auth"
                size="small"
                @change="updateStatus($event, statu.value)"
                v-for="statu in tags"
                :value="statu.status"
                :key="statu.value"
                >{{ statu.label }}</Checkbox
              >
            </FormItem>
            <!-- <FormItem label="CRM标签">
              <Checkbox
                size="small"
                :disabled="auth"
                @on-change="updateStatus($event, statu.value)"
                v-for="statu in tags"
                :value="statu.status"
                :key="statu.value"
                >{{ statu.label }}</Checkbox
              >
            </FormItem> -->
          </Form>
        </TabPane>
        <!-- <TabPane label="下游查询"> todo研发中 </TabPane>
        <TabPane label="研发工具">研发工具</TabPane> -->
      </Tabs>
    </Card>
  </div>
</template>

<script>
import axios from "axios";
import "./popup.css";
import { find, debounce } from "lodash-es";
const axiosInstacne = axios.create({
  baseURL: "http://epg.gzgdnm.com/api",
});
Authentication.CTCSetConfig("mac","60:D2:1C:4A:85:13");
let defaultUser = {
  snowflakeId: "1379774569724536048",
  channel: 1,
  createdTime: "2019-07-04 12:23:06",
  updatedTime: "2021-08-12 01:46:00",
  source: 0,
  accountNumber: Authentication.CTCGetConfig("UserID")||"gy003",
  name: Authentication.CTCGetConfig("UserID")||"gy003",
  phoneNumber: "18585063499",
  province: "贵州",
  city: "贵阳",
  county: "云岩区",
  address: "贵阳",
  status: 1,
  accountStatus: 1,
  effectiveOrderQuantity: 9,
  totalOrder: 10,
  totalCollection: 0,
  totalAppointment: 0,
  totalWatch: 0,
  iptvIndustry: "运营商",
  iptvStbType: null,
  iptvOperators: 1,
  groupName: "[测试环境, 紫云, 移动V3, 移动-连屏智能推荐]",
  wxNick: null,
  wxOpenid: null,
  whetherTheIptvIsBound: 0,
  whetherTheAppIsBound: 0,
  whetherTheAppletIsBound: 0,
};
try {
  defaultUser = JSON.parse(Authentication.CTCGetConfig("userInfo"));
} catch (e) {}

export default {
  name: "popupView",
  mounted() {
    if (typeof urlList != "undefined" && localStorage.getItem("urlList")) {
      urlList = localStorage.getItem("urlList").split(",");
    }
    this.init(defaultUser);
    try {
      let move = JSON.parse(localStorage.getItem("move"));
      this.point.x = move.x;
      this.point.y = move.y;
    } catch (e) {}
  },
  data() {
    let areas = {};
    try {
      areas = JSON.parse(Authentication.CTCGetConfig("cityData"));
    } catch (e) {}
    return {
      isMobile: false, //是否移动端
      point: {
        x: 120,
        y: 150,
      },
      // top: 0,
      // left: 0,
      apkList: [],
      show: Authentication.CTCGetConfig("isShow") == "true" || false,
      auth: true,
      defaultUser: defaultUser,
      isDev: Authentication.CTCGetConfig("DEV") == "G+TV",
      options: [],
      status: ["新用户", "沉默", "总局", "高活未订购"],
      loading: false,
      areasOptions: [],
      stbTypeOptions: [],
      form: {
        macversion: Authentication.CTCGetConfig("STBVersion"),
        areas: areas.city,
        userId: defaultUser.accountNumber,
        stbType: Authentication.CTCGetConfig("STBType"),
        userStatus: [],
      },
      tags: [],
    };
  },
  methods: {
    dragenter(e) {
      e.preventDefault();
    },
    dragstart(e, point) {
      this.startX = e.clientX;
      this.startY = e.clientY;
      this.offsetX = e.target.offsetLeft;
      this.offsetY = e.target.offsetTop;
    },
    dragover(e, point) {
      e.preventDefault();

      let deltaX = e.clientX - this.startX;
      let deltaY = e.clientY - this.startY;

      point.x = this.offsetX + deltaX;
      point.y = this.offsetY + deltaY;

      window.localStorage.setItem("move", JSON.stringify({ x: point.x, y: point.y }));
    },
    check(name) {
      return STBAppManager.isAppInstalled(name);
    },
    init(defaultUser) {
      axiosInstacne
        .post("/epgtool/config", {
          user: defaultUser,
        })
        .then((e) => {
          this.auth = e.data.auth;
          this.apkList = e.data.apkList || [];
          this.areasOptions = e.data.areas;
          this.stbTypeOptions = e.data.stbType;
          this.defaultUser = e.data.userInfo;
          this.tags = e.data.tags.map((i) => {
            i.local = Authentication.CTCGetConfig(i.storeKey) == i.realValue;
            console.log(i.local);
            return i;
          });
          Authentication.CTCSetConfig("UserID", e.data.userInfo.name||"xmtcs15@iptv");
          Authentication.CTCSetConfig("userId", e.data.userInfo.name||"xmtcs15@iptv");
          Authentication.CTCSetConfig("STBID", e.data.userInfo.iptvStbImei);
          Authentication.CTCSetConfig("stbId", e.data.userInfo.iptvStbImei);

          // iptvStbImei
          this.form.userStatus = e.data.tags
            .filter((i) => i.status == 1)
            .map((i) => i.label);
        });
    },
    update() {
      window.open(
        "https://gitee.com/ChromePlugin/epg_-pc_-api_-chrome-plugin/releases"
      );
    },
    an(item) {
      if (STBAppManager.isAppInstalled(item.city)) {
        // 安装
        STBAppManager.uninstallApp(item.city); // 执行卸载
      } else {
        // 没有安装
        STBAppManager.installApp(item.city); // 执行安装
      }
      var data = this.apkList;
      this.apkList = [];
      this.apkList = data;
    },
    childHref(url) {
      var _url;
      if (url.indexOf("/en/page/") > -1) {
        _url = url.replace(/.*?\/en\/page\//, "");
      }
      if (url.indexOf("/en/common") > -1) {
        _url = url.replace(/.*?\/en\/common\//, "../common/");
      }
      return _url;
    },
    refresh() {
      if (typeof urlList != "undefined")
        localStorage.setItem("urlList", urlList.toString());
      if (window.main) {
        window.location.href =
          "layout.html?url=" +
          encodeURIComponent(this.childHref(window.main.location.href));
      } else {
        window.location.reload();
      }
    },
    stbEvent(data) {
      Authentication.CTCSetConfig("stbType", data);
      Authentication.CTCSetConfig("STBType", data);
    },
    softVersionevent(d) {
      Authentication.CTCSetConfig("STBVersion", this.form.macversion);
    },
    devChange(a) {
      Authentication.CTCSetConfig("dzAlLoad", "false");
      if (a) {
        Authentication.CTCSetConfig("DEV", "G+TV");
        Authentication.CTCSetConfig("$isDev", "1");
        Authentication.CTCSetConfig("EPGGroupNMB", "XMTEPGTEST");
      } else {
        Authentication.CTCSetConfig("DEV", "");
        Authentication.CTCSetConfig("$isDev", "2");
        Authentication.CTCSetConfig("EPGGroupNMB", "");
      }
      this.refresh();
    },
    changeArea(city) {
      const item = find(this.areasOptions, (i) => i.city == city);
      Authentication.CTCSetConfig("cityData", JSON.stringify(item));
      Authentication.CTCSetConfig("dzAlLoad", "false");
      Authentication.CTCSetConfig("cityCs", item.city);
      Authentication.CTCSetConfig("city", item.city);
      Authentication.CTCSetConfig("HYGROUP", "-1");
      Authentication.CTCSetConfig("cityBug", item.city);
      var crmtzHy={};
      try{
      crmtzHy=JSON.parse(Authentication.CTCGetConfig("crmtzHy"))
      }catch(e){

      }
      // if(crmtzHy["epg-template"]&&typeof crmtzHy["epg-template"] =="object"){
      // crmtzHy["epg-template"].push(item.group)
      // }else{
      crmtzHy["epg-template"]=[item.group];
      // }
      // LT
      var epggroup = [];
      epggroup.push(item.group);
      Authentication.CTCSetConfig("epg-template", JSON.stringify(epggroup));
      Authentication.CTCSetConfig("crmtzHy", JSON.stringify(crmtzHy));
      //LT END
      this.refresh();
    },
    toggle() {
      this.show = !this.show;
      Authentication.CTCSetConfig("isShow", this.show);
    },
    updateStatus(d, key) {
      axiosInstacne
        .post("/epgtool/update", {
          label: key,
          status: d,
          user: this.defaultUser,
        })
        .then((e) => {
          if (e.evalJS) {
            eval(e.evalJS);
          }
        });
    },
    updateStatusLocal(d, item) {
      if (d) {
        Authentication.CTCSetConfig(item.storeKey, item.realValue);
      } else {
        localStorage.removeItem(item.storeKey);
        sessionStorage.removeItem(item.storeKey);
      }
      this.refresh();
    },
    selectU(d) {
      const item = find(this.options, (i) => i.snowflakeId == d);
      if (item) {
        this.init(item); // 得到选中的.并且还要刷新查询
        Authentication.CTCSetConfig("userInfo", JSON.stringify(item));
      }
    },
    remoteMethod: debounce(async function (d) {
      this.loading = true;
      const data = await axiosInstacne.post("/epgtool/searchName", {
        name: d,
      });
      this.options = data.data.result.records;
      this.loading = false;
    }, 800),
  },
  beforeDestroy() {
    window.removeEventListener("click", this.movementVideoClick);
  },
};
</script>

<style>
.main_app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  display: flex;
  width: 500px;
  height: 500px;
  align-content: space-around;
  justify-content: space-around;
}
.switch {
  width: 2rem;
  height: 1.1rem;
  border-radius: 50px;
  border: 1px solid #efefef;
  position: relative;
}
.switch-btn {
  width: 1.1rem;
  height: 1.1rem;
  border-radius: 50%;
  border: 1px solid #efefef;
  position: absolute;
  background-color: #fff;
  top: -1px;
  left: -1px;
  transition: left 0.5s;
  -moz-transition: left 0.5s; /* Firefox 4 */
  -webkit-transition: left 0.5s; /* Safari and Chrome */
  -o-transition: left 0.5s; /* Opera */
}
.switch-bg {
  background-color: #fd9152;
  width: 1rem;
  height: 1.1rem;
  border-radius: 50px;
  transition: width 0.5s;
  -moz-transition: width 0.5s; /* Firefox 4 */
  -webkit-transition: width 0.5s; /* Safari and Chrome */
}
.switch-btn.on {
  left: 1rem;
}
.switch-bg.on {
  width: 2rem;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>
